import { Component } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { ApesModalService } from '@shared/apes/modal';

import { ApesUploadDialogComponent } from '@shared/ag-grid-ext/upload-component';
import { UploadFile } from '@shared/apes/upload';
import { deepClone } from '../../../utils/utils';
import { SubjectService } from '@core/services/events/subject.service';
import { ApesPreviewDialogComponent } from '../upload-component/apes-previewDialog.component';

@Component({
  selector: 'apes-cell-upload',
  template: `
    <div class="apes-cell-upload">
      <ng-container *ngIf="!hideUpload">
        <button apesType="link" apes-button class="apes-upload-button" (click)="clickUpload()" [disabled]="disabled">
          <i apes-icon apesType="plus"></i>
        </button>
      </ng-container>
      <ng-container *ngIf="showFileList() && showImg">
        <button apesType="link" apes-button class="apes-upload-button" (click)="showPhoto()">
          <i apes-icon apesType="picture"></i>
        </button>
      </ng-container>
      <ng-container *ngIf="showFileList() && !showImg">
        <button apesType="link" apes-button class="apes-upload-button" (click)="showFile()">
          <i apes-icon apesType="file"></i>
        </button>
      </ng-container>
    </div>
  `,
  styles: [`
    .apes-cell-upload {
      text-align: center;
    }

    .apes-upload-button {
      padding: 6px;
    }
  `],
})
export class RenderUploadComponent implements ICellRendererAngularComp {

  params: any;
  ctx: any;
  key: any;
  data: any;
  limit: any = 3;
  type: any;
  imgType: any = 'image/png,image/jpeg,image/gif,image/bmp,image/tif';
  limitedType: any;
  showImg: boolean = true;
  accept: any;
  hideUpload: boolean = false;
  _fileList: any[] = [
    // {
    //   fileName: 'QQ截图20190114101913.jpg',
    //   iconType: 'thumbnail',
    //   id: '5eafb54488ecd61924a9dd10',
    //   isImageUrl: true,
    //   isUploading: false,
    //   linkProps: undefined,
    //   listItemNameCls: '{apes-upload-list-item-name: true, apes-upload-list-item-name-icon-count-1: true}',
    //   message: '上传错误',
    //   name: 'QQ截图20190114101913.jpg',
    //   showDownload: false,
    //   size: 337580,
    //   type: 'image/jpeg',
    //   url: 'fileserver/view/5eafb54488ecd61924a9dd10',
    // },
    // {
    //   fileName: 'B01075000407.090924.png',
    //   id: '',
    //   name: 'B01075000407.090924.png',
    //   size: 0,
    //   type: 'image/jpeg',
    //   url: 'https://cdn.91autoparts.com/epc/benz/181126/B01075000407.090924.png',
    // },
    // {
    //   fileName: 'B01075000407.090924.png',
    //   id: '',
    //   name: 'B01075000407.090924.png',
    //   size: 0,
    //   type: 'image/jpeg',
    //   url: 'https://cdn.91autoparts.com/epc/benz/181126/B01075000407.090924.png',
    // },
    // {
    //   fileName: 'B01075000407.090924.png',
    //   id: '',
    //   name: 'B01075000407.090924.png',
    //   size: 0,
    //   type: 'image/jpeg',
    //   url: 'https://cdn.91autoparts.com/epc/benz/181126/B01075000407.090924.png',
    // },
    // {
    //   fileName: 'B01075000407.090924.png',
    //   id: '',
    //   name: 'B01075000407.090924.png',
    //   size: 0,
    //   type: 'image/jpeg',
    //   url: 'https://cdn.91autoparts.com/epc/benz/181126/B01075000407.090924.png',
    // },
    // {
    //   fileName: 'B01075000407.090924.png',
    //   id: '',
    //   name: 'B01075000407.090924.png',
    //   size: 0,
    //   type: 'image/jpeg',
    //   url: 'https://cdn.91autoparts.com/epc/benz/181126/B01075000407.090924.png',
    // },
  ];
  gridName: any;
  disabled = true;
  multiple: boolean = false;

  constructor(
    private modalService: ApesModalService,
    protected subject: SubjectService,
  ) {
  }

  agInit(params: any): void {
    this.params = params;

    let colDef = params.hasOwnProperty('colDef') ? params.colDef : params.column['colDef'];
    this.key = deepClone(colDef['field']);
    this.limit = colDef['limit'];
    this.type = colDef['type'];
    this.disabled = colDef['cellDisabled'];
    this.multiple = colDef['multiple'];
    this.accept = colDef['accept'];
    this.hideUpload = colDef['hideUpload'];

    if(params.context){
      this.ctx = params.context;
      this.gridName = this.ctx['gridName'];
    }
    if (this.params.hasOwnProperty('colDef')) {
      this.data = this.params.data;
    } else {
      this.data = this.params.node.data;
    }
    if (this.type) {
      if (this.imgType.indexOf(this.type) > -1) {
        this.limitedType = this.type;
        this.showImg = true;
      } else if (this.type == 'all') {
        this.limitedType = undefined;
        this.showImg = false;
      } else {
        this.limitedType = this.type;
        this.showImg = false;
      }
    } else {
      this.limitedType = this.imgType;
      this.showImg = true;
    }
    setTimeout(() => {
      if (this.data[this.key]) {
        let data = deepClone(this.data[this.key]);
        if (typeof data === 'string') {
          this.fileList = JSON.parse(data);
        } else {
          if (this.type == 'tif') {
            let list = [];
            data.forEach((res) => {
              // res = res.replace(/.tif/,'.TIF');
              list.push({ tifSrc: res });
            });
            this.fileList = list;
          } else if (this.showImg && typeof data[0] === 'string') {
            let list = [];
            data.forEach((res) => {
              // if (res.indexOf(';') > -1) {
              //   let re = res.split(';');
              //   re.forEach((r) => {
              //     list.push({ url: r });
              //   });
              // } else {
              list.push({ url: res });
              // }
            });
            this.fileList = list;
          } else {
            this.fileList = data;
          }
        }
      } else {
        this.fileList = [];
      }
    }, 500);
  }

  extend(data: any) {
    let result = {};
    for (let key in data) {
      let value = data[key];
      if (key === 'context') {
        result['ctx'] = value;
      } else {
        result[key] = value;
      }
    }
    return result;
  }

  ngAfterViewInit() {
  }

  get fileList(): UploadFile[] {
    return this._fileList || [];
  }

  set fileList(input: UploadFile[]) {
    let value = input;
    if (this._fileList === value) {
      return;
    }
    this._fileList = value;
  }

  clickUpload() {
    // let type;
    // if (this.type) {
    //   type = this.type;
    // }
    let option = {
      title: this.showImg ? '上传图片' : '上传文件',
      limit: this.limit,
      type: this.limitedType,
      accept: this.accept,
      showDownload: true,
      showRemove: true,
      _fileList: this.fileList,
      multiple: this.multiple ? this.multiple : false,
    };


    this.openUploadDialog(option, (result: any) => {
      if (result) {
        this.fileList = result;
        this.params.value = result;
        // this.params.node.setDataValue(this.key, null);
        // this.params.data = this.fileList;
        this.params.node.setDataValue(this.key, this.fileList);
        this.params.api.updateRowData(this.params.node.data);
      }
    });
  }

  showPhoto() {
    let dialog: any = ApesPreviewDialogComponent;
    let fileList = deepClone(this.fileList);
    let option = {
      title: '预览图片',
      _fileList: fileList,
    };

    this.openUploadDialog(option, (result: any) => {
      // console.log(result);
    }, dialog);

  }

  showFile() {
    // let dialog: any = ApesPreviewDialogComponent;
    let fileList = deepClone(this.fileList);
    let option = {
      title: '预览文件',
      _fileList: fileList,
      showRemove: false,
      showFile: true,
    };

    this.openUploadDialog(option, (result: any) => {
      // console.log(result);
    });
  }

  openUploadDialog(option: any, callback: any, dialog?: any) {

    let body: any = { ...option };

    const openDialog = dialog ? dialog : ApesUploadDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '45vw',
      apesTitle: body.title,
      apesContent: openDialog,
      apesComponentParams: body,
      apesMaskClosable : false,
      apesClosable: false,
      apesFooter: [
        // {
        //   label: '取消',
        //   type: 'default',
        //   onClick: (componentInstance) => {
        //     dialogRef.destroy(componentInstance['fileList']);
        //     // dialogRef.close();
        //   },
        // },
        {
          label: '返回',
          type: 'primary',
          disabled: (componentInstance) => {
            return componentInstance['uploading'];
          },
          onClick: (componentInstance) => {
            // console.log(componentInstance);
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
      ],
    });

    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

  showFileList() {
    return this.fileList.length != 0;
  }


  getValue(): any {
    let result;
    if (this.fileList.length == 0) {
      result = [];
      this.params.value = [];
    } else {
      result = this.fileList;
      this.params.value = this.fileList;
    }
    return result;
  }

  refresh(params: any): boolean {
    // params.data[this.params['colDef']] = params.value;
    // params.api.refreshCells(params);
    return false;
  }

}
